<template>
  <view class="padding-10">
    <block v-for="(item,index) in templateList" :key="index">
      <view class="mainColor border-10 colorB" style="border: 1px solid #fff;margin-bottom: 20rpx;">
        <view class="padding-10">
          模板名称：{{item.name}}
        </view>
        <view class="padding-10">
          模板备注：{{item.remark}}
        </view>
        <view class="padding-10">
          车辆类型：{{vehicleType(item.type)}}
        </view>
        <view class="padding-10">
          创建时间：{{item.createTime}}
        </view>
        <view class="padding-10">
          更新时间：{{item.updateTime || '一'}}
        </view>
        <view class="padding-10 ">
          操作：
          <text class="color0" style="margin-right: 20rpx;" @click="handleUpdate(item)">修改</text>
          <!-- <text style="color: aqua;">删除</text> -->
        </view>
      </view>
    </block>
    <pagination :queryParams="queryParams" :total="total" @changeNum="changeNum" @changeSize="changeAdd" @reset="reset">
    </pagination>
    <uni-popup ref="popup" type="bottom" background-color="#fff" style="color: #040f25;margin-top: 80%;">
      <scroll-view scroll-y="true" scroll-top="0" class="scroll-Y">
        <uni-forms ref="customForm" :rules="customRules" :modelValue="form">
          <uni-forms-item label="类型">
            <uni-easyinput type="text" :value="form.type === 1?'电动汽车':'电动自行车'" disabled />
          </uni-forms-item>
          <uni-forms-item label="名称" required name="name">
            <uni-easyinput v-model="form.name " placeholder="请输入模板名称" />
          </uni-forms-item>
          <uni-forms-item label="描述" required name="remark">
            <uni-easyinput v-model="form.remark" placeholder="请输入模板备注" width="" />
          </uni-forms-item>
          <uni-forms-item label="尖时段电费(元/度)" required name="electricityPriceA" :labelWidth='150'>
            <uni-easyinput v-model="form.electricityPriceA" />
          </uni-forms-item>
          <uni-forms-item label="尖时段服务费(元/度)" required name="servicePriceA" :labelWidth='150'>
            <uni-easyinput v-model="form.servicePriceA" />
          </uni-forms-item>
          <uni-forms-item label="峰时段电费(元/度)" required name="electricityPriceB" :labelWidth='150'>
            <uni-easyinput v-model="form.electricityPriceB" />
          </uni-forms-item>
          <uni-forms-item label="峰时段服务费(元/度)" required name="servicePriceB" :labelWidth='150'>
            <uni-easyinput v-model="form.servicePriceB" />
          </uni-forms-item>
          <uni-forms-item label="平时段电费(元/度)" required name="electricityPriceC" :labelWidth='150'>
            <uni-easyinput v-model="form.electricityPriceC" />
          </uni-forms-item>
          <uni-forms-item label="平时段服务费(元/度)" required name="servicePriceC" :labelWidth='150'>
            <uni-easyinput v-model="form.servicePriceC" />
          </uni-forms-item>
          <uni-forms-item label="谷时段电费(元/度)" required name="electricityPriceD" :labelWidth='150'>
            <uni-easyinput v-model="form.electricityPriceD" />
          </uni-forms-item>
          <uni-forms-item label="谷时段服务费(元/度)" required name="servicePriceD" :labelWidth='150'>
            <uni-easyinput v-model="form.servicePriceD" />
          </uni-forms-item>
        </uni-forms>
        <uni-title title="24小时尖峰平谷分布设置" type="h3"></uni-title>
        <view>
          <view class="labelStyle" :key="item.label" v-for="item in dynamicTags" :type="item.type" effect="dark">
            {{item.label}}
            <u-icon name="edit-pen" @click="editBtn(item.label)"></u-icon>
            <uni-icons type="closeempty" @click="deleteBtn(item.label)"></uni-icons>
          </view>
          <button @click="addBtn">增加计费时段</button>
        </view>
      </scroll-view>
      <button type="primary" @click="submit('customForm')">提交</button>
    </uni-popup>
    <uni-popup ref="updateTimePopup" type="bottom" backgroundColor="#fff" style="color: #040f25;margin-top: 80%;">
      <uni-title title="设置计费时段" />
      <p>开始时间</p>
      <picker mode="time" :value="startTime" start="00:00" end="24:00" @change="bindTimeChange"
        :disabled="selectDisabled === false">
        <view class="uni-input">{{startTime}}</view>
      </picker>
      <p>标签</p>
      <radio-group @change="radioChange">
        <radio value="1" :checked="radioValue == 1 " />尖
        <radio value="2" :checked="radioValue == 2" />峰
        <radio value="3" :checked="radioValue == 3 " />平
        <radio value="4" :checked="radioValue == 4 " />谷
      </radio-group>
      <button @click="clickSelectStartTimeConfirm">确定</button>
    </uni-popup>
  </view>
</template>

<script>
  import {
    listTemplate,
    getTemplate,
    addBillingTemplate,
    updateBillingTemplate
  } from "@/api/billing/template";
  import {
    vehicleType
  } from '@/common/dict.js'
  export default {
    data() {
      return {
        selectDisabled: false,
        radioValue: null,
        templateList: [],
        queryParams: {
          pageNum: 1,
          pageSize: 10,
        },
        total: 0,
        vehicleList: [],
        // 电动汽车
        form: {
          electricityPriceA: "",
          servicePriceA: "",
          electricityPriceB: "",
          servicePriceB: "",
          electricityPriceC: "",
          servicePriceC: "",
          electricityPriceD: "",
          servicePriceD: "",
          timeArray: [{
            type: "1",
            startTime: "00:00",
            endTime: "24:00",
          }, ],
          type: "1",
          name: "",
          remark: "",
          minMoney: "",
          minute: "",
        },
        type: [{
          text: '电动汽车',
          value: 0
        }, {
          text: '电动自行车',
          value: 1
        }],
        // 开始时间
        startTime: "",
        // 结束时间
        endTime: "",
        // 标签 单选框
        radio: 3,
        // 自定义表单校验规则
        customRules: {
          name: {
            rules: [{
              required: true,
              errorMessage: '姓名不能为空'
            }]
          },
          age: {
            rules: [{
              required: true,
              errorMessage: '年龄不能为空'
            }]
          },
          hobby: {
            rules: [{
                format: 'array'
              },
              {
                validateFunction: function(rule, value, data, callback) {
                  if (value.length < 2) {
                    callback('请至少勾选两个兴趣爱好')
                  }
                  return true
                }
              }
            ]
          }

        },
        dynamicFormData: {
          email: '',
          domains: {}
        },
        dynamicLists: [],
        dynamicRules: {
          email: {
            rules: [{
              required: true,
              errorMessage: '域名不能为空'
            }, {
              format: 'email',
              errorMessage: '域名格式错误'
            }]
          }
        }
      };
    },
    computed: {
      dynamicTags() {
        let tags = [];
        this.form.timeArray.map((x) => {
          // console.log(x.type);
          let type;
          let desc;
          if (x.type === "1") {
            type = "error"; // 
            desc = "尖";
          } else if (x.type === "2") {
            type = "warning"; // warning
            desc = "峰";
          } else if (x.type === "3") {
            type = "success"; // success
            desc = "平";
          } else {
            type = "info"; // info
            desc = "谷";
          }
          let label = desc + " - " + x.startTime + " - " + x.endTime;
          let tag = {
            type: type,
            label: label,
          };
          tags.push(tag);
        });
        return tags;
      },
    },
    onReady() {
      // 设置自定义表单校验规则，必须在节点渲染完毕后执行
      this.$refs.customForm.setRules(this.customRules)
    },
    methods: {
      addBtn() { // 新增计费时段
        this.selectDisabled = true
        this.radioValue = 1
        console.log("radioValue", this.radioValue);
        this.startTime = '01:00';
        this.$refs.updateTimePopup.open()
      },
      bindTimeChange: function(e) {
        console.log(e, 'disabled');
        this.startTime = e.detail.value
      },
      clickSelectStartTimeConfirm() {
        let e = {
          startTime: this.startTime,
          type: this.radio,
        };
        // startTime在原数组中存在，把老的删掉
        this.selectStartTime = this.selectStartTime.filter(
          (item) => item.startTime !== this.startTime
        );
        // 新时间插入数组最后
        this.selectStartTime.push(e);
        // selectStartTime根据startTime排序
        this.selectStartTime.sort((a, b) =>
          a.startTime.localeCompare(b.startTime)
        );
        // 调生成方法
        this.generateTimeArray();
        this.$refs.updateTimePopup.close()
      },
      // 生成timeArray
      generateTimeArray() {
        // 原来的timeArray初始化为空数组
        this.form.timeArray = [];
        // 使用selectStartTime中的数据重新生成数据
        for (let i = 0; i < this.selectStartTime.length; i++) {
          let start = this.selectStartTime[i];
          let end = this.selectStartTime[i + 1];
          // 遍历到最后一位时，取不到end，就给默认结束时间24:00
          if (end === undefined) {
            end = {
              startTime: "24:00",
            };
          }
          let time = {
            type: String(start.type),
            startTime: start.startTime,
            endTime: end.startTime,
          };
          this.form.timeArray.push(time);
        }
      },
      radioChange(e) {
        console.log(e.detail.value);
        this.radioValue = e.detail.value
      },
      editBtn(param) {
        this.selectDisabled = false
        const splitArr = param.split("-");
        const editType = splitArr[0].trim();
        if (editType === "尖") {
          this.radioValue = 1;
        } else if (editType === "峰") {
          this.radioValue = 2;
        } else if (editType === "平") {
          this.radioValue = 3;
        } else {
          this.radioValue = 4;
        }
        console.log("radioValue", this.radioValue);
        this.startTime = splitArr[1].trim();
        this.$refs.updateTimePopup.open()
      },
      deleteBtn(param) {
        const splitArr = param.split("-");
        const delObj = splitArr[1].trim();
        if (delObj === "00:00") {
          return;
        }
        this.selectStartTime = this.selectStartTime.filter(
          (item) => item.startTime !== delObj
        );
        // 调生成方法
        this.generateTimeArray();
      },
      queryInfo(billingTemplateId) {
        getTemplate(billingTemplateId).then((response) => {
          console.log("更新计费模板 查询计费模板详情", response);
          this.form = response.data;
          console.log("timeArray", this.form.timeArray);
          const selectStartTimeArr = [];
          this.form.timeArray.forEach(x => {
            const startTime = {
              startTime: x.startTime,
              type: x.type
            };
            selectStartTimeArr.push(startTime);
          })
          this.selectStartTime = selectStartTimeArr;
        });
      },
      handleUpdate(e) { // 修改按钮
        this.$refs.popup.open()
        this.queryInfo(e.id)
      },
      submit(ref) {
        this.$refs[ref].validate().then(res => {
          console.log('success', res);
          if (this.billingTemplateId === '') {
            // 没有id 新增
            this.create();
          } else {
            // 存在id 更新
            this.update();
          }
        }).catch(err => {
          console.log('err', err);
        })
      },
      create() {
        addBillingTemplate(this.form).then((response) => {
          console.log("接口返回", response);
          this.$message.success("新增成功");
        });
      },
      update() {
        // this.$set(this.form, 'billingTemplateId', this.billingTemplateId);
        updateBillingTemplate(this.form).then((response) => {
          console.log("接口返回", response);
          this.getList()
          this.$refs.popup.close()
        });
      },
      getList() {
        listTemplate(this.queryParams).then((response) => {
          this.templateList = response.rows;
          this.total = response.total;
        });
      },
      vehicleType(type) {
        vehicleType.then(res => this.vehicleList = res)
        let arr = this.vehicleList.find(item => item.dictValue == type)
        if (arr == null) {
          return '一'
        } else {
          return arr.dictLabel
        }
      },
      // 组件传递的事件 0
      changeNum(e) {
        this.queryParams.pageNum = e
        this.getList()
      },
      changeAdd(e) {
        this.queryParams.pageSize = e
        this.getList()
      },
      reset() {
        this.queryParams.pageSize = 10
        this.queryParams.pageNum = 1
        this.getList();
      },
    },
    onLoad() {
      this.getList()
    }
  }
</script>

<style lang="scss" scoped>
  .scroll-Y {
    height: 400rpx;
  }

  .labelStyle {
    margin: 10px 10px 10px 0;
    width: 160px;
    height: 30px
  }
</style>